package com.gdt.bdMessageQueue.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.ActiveMQConnectionFactory;
 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.gdt.bdMessageQueue.pojo.ActiveMqMonitor;

import javax.jms.*;

@Component
@Scope("prototype")
public class Server implements MessageListener {
	
	
    private static int ackMode;
    private static String messageBrokerUrl;
 
    private Session session;
    private Connection connection;
    
    private boolean transacted = false;
    
    private MessageProducer replyProducer;
    private MessageConsumer messageConsumer;
    private MessageService messageService;
    
    private String queueName;
    
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    
    @Autowired
	ActiveMqMonitorService acMService;
    /*private static Server server =null;*/
 
    static {
        messageBrokerUrl = "tcp://localhost:61616";
        ackMode = Session.AUTO_ACKNOWLEDGE;
    }
    
   /* public static Server getInstance(){
    	if(server == null){
    		server = new Server();
    	}
    	return server;
    }*/
 
    public Server() {
        try {
            BrokerService broker = new BrokerService();
            broker.setPersistent(false);
            broker.setUseJmx(false);
            broker.addConnector(messageBrokerUrl);
            broker.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
       
    }
    
    
    
    public void startConnect(String queueName){
          this.messageService = new MessageService();
          this.setupMessageQueueConsumer(queueName);
    }
    
    
 
    private void setupMessageQueueConsumer(String queueName) {
    	this.queueName = queueName;
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(messageBrokerUrl);
        Connection connection;
        try {
            connection = connectionFactory.createConnection();
            this.connection =connection;
            connection.start();
            this.session = connection.createSession(this.transacted, ackMode);
            Destination adminQueue = this.session.createQueue(queueName);
            this.replyProducer = this.session.createProducer(null);
            this.replyProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            MessageConsumer consumer = this.session.createConsumer(adminQueue);
            this.messageConsumer = consumer;
            consumer.setMessageListener(this);
        } catch (JMSException e) {
           e.printStackTrace();
        }
    }
    
    public void stopSession(){
    	try {
    		/*this.replyProducer.close();
    		this.messageConsumer.close();
			this.session.close();*/
			this.connection.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
    }
 
    public void onMessage(Message message) {
        try {
            TextMessage response = this.session.createTextMessage();
            if (message instanceof TextMessage) {
                TextMessage txtMsg = (TextMessage) message;
                String messageText = txtMsg.getText();
                System.out.println("receiver message is "+ messageText);
                
                ActiveMqMonitor aqM = acMService.getActiveMqMonitorByQueueName(queueName);
       		 	Date startTime = aqM.getStartServiceTime();
       		 	Date stopTime = aqM.getStopServiceTime();
       		 	try {
       		 		Date time = dateFormat.parse(dateFormat.format(new Date()));
       			if(acMService.isTimeIn(time, startTime, stopTime)){
       				
       				response.setText(this.messageService.handleProtocolMessage(messageText));
       			}else{
       				response.setText("服务已过期");
       			}
       			
       		} catch (ParseException e) {
       			// TODO Auto-generated catch block
       			e.printStackTrace();
       			response.setText("服务出现异常");
       		}
            }
 
            response.setJMSCorrelationID(message.getJMSCorrelationID());
 
            this.replyProducer.send(message.getJMSReplyTo(), response);
        } catch (JMSException e) {
           e.printStackTrace();
        }
    }
 
   /* public static void main(String[] args) {
    	String quName =args[0];
    	System.out.println("传入消费者的监听queueName is "+ quName);
        new Server(quName);
    }*/
}